<template>
  <div class="course-list">
    <el-card shadow="never" style="margin-bottom: 20px; border: none;">
      <el-form :model="searchInfo" inline class="course-form">
        <el-form-item label="课程名称：">
          <el-input v-model="searchInfo.search" placeholder="请输入课程名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" style="border: none;">
      <div class="course-list__operate">
        <el-button type="primary" @click="openDialog('create')">创建课程</el-button>

        <el-button
          type="danger"
          :disabled="selected.length <= 0"
          @click="removeCourse(selected)"
        >
          批量删除
        </el-button>
      </div>
      <el-table
        ref="elTableRef"
        v-loading="loading"
        :data="list"
        border
        :row-key="getRowKey"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :selectable="disableSelection"
          :reserve-selection="true"
        />
        <el-table-column label="课程名称" align="center" prop="title" />
        <el-table-column label="封面" align="center" prop="cover">
          <template v-slot="{ row }">
            <el-image :src="row.cover" style="width: 50px;height: 50px;">
              <div slot="error">
                <div class="image-slot">暂无图片</div>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="学习周期（天）" align="center" prop="day" />
        <el-table-column label="课程时长" align="center" prop="duration" />
        <el-table-column label="创建时间" align="center" prop="created_at" />
        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <el-button
              type="text"
              size="mini"
              @click="editCourse(row)"
            >
              编辑
            </el-button>

            <el-button
              :title="row.isInUse ? '已下发课程无法删除' : ''"
              :disabled="row.isInUse"
              type="text"
              size="mini"
              style="color: #F56C6C;"
              @click="removeCourse(row)"
            >
              删除
            </el-button>

            <el-dropdown @command="handleCommand($event, row)">
              <el-button type="text" style="margin-left: 10px;">
                <i class="el-icon-more" />
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="toDetail">查看详情</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

          </template>
        </el-table-column>

      </el-table>
      <div>
        <Pagination
          style="padding-bottom: 0; margin-top: 0;"
          :total="total"
          :limit="pagination.paginate"
          :page="pagination.page"
          @pagination="handlePagination"
        />
      </div>
    </el-card>

    <CourseDialog
      ref="courseDialogRef"
      v-model="dialogCfg.visible"
      :title="dialogCfg.title"
      :submit-loading="dialogCfg.loading"
      @onConfirm="courseDialogConfirm"
    />
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import CourseDialog from '@/views/train/components/Course/CourseDialog.vue'

import {
  getCourseList,
  createOrUpdateCourse,
  deleteCourse,
  getCourseDetails
} from '@/api/v2/course'
import { isArray } from '@/utils/kris_utils'
export default {
  components: {
    Pagination,
    CourseDialog
  },
  data() {
    return {
      loading: false,
      searchInfo: {
        search: ''
      },
      pagination: {
        page: 1,
        paginate: 10
      },
      total: 0,
      list: [],
      dialogCfg: {
        visible: false,
        title: '创建课程',
        loading: false
      },
      selected: []
    }
  },
  created() {
    this.init()
  },
  methods: {

    getRowKey(row) {
      return row.id
    },

    disableSelection(row) {
      return !row.isInUse
    },

    init() {
      this.getCourseList()
    },

    handleCommand(e, row) {
      this[e](row)
    },

    toDetail(row) {
      this.$router.push({
        path: `/train/detail/${row.id}`
      })
    },

    handleError(error, defaultMessage) {
      const errMsg = error?.response?.data?.message || defaultMessage
      this.$message.error(errMsg)
    },

    async getCourseList() {
      this.loading = true
      try {
        const res = await getCourseList({ ...this.searchInfo, ...this.pagination })
        this.list = res.data
        this.total = res.meta.total
      } catch (error) {
        this.handleError(error, '获取课程列表失败！')
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      this.pagination.page = 1
      this.getCourseList()
    },

    openDialog(type, row) {
      if (type === 'create') {
        this.dialogCfg.title = '创建课程'
      }
      this.dialogCfg.visible = true
      this.$nextTick(() => {
        this.$refs.courseDialogRef.resetFields()
      })
    },

    handlePagination(e) {
      this.pagination.paginate = e.limit
      this.pagination.page = e.page
      this.getCourseList()
    },

    async courseDialogConfirm(e) {
      const data = {
        ...e,
        data: JSON.stringify(e.data)
      }
      if (!e.course_id) {
        await this.createCourse(data)
      } else {
        await this.updateCourse(data)
      }
    },

    async createCourse(data) {
      this.dialogCfg.loading = true
      try {
        await this.createOrUpdateCourse(data)
        this.$message.success('课程创建成功')
        this.refresh()
      } catch (error) {
        this.handleError(error, '课程创建失败')
      } finally {
        this.dialogCfg.loading = false
      }
    },

    async updateCourse(data) {
      this.dialogCfg.loading = true
      try {
        await this.createOrUpdateCourse(data)
        this.$message.success('课程修改成功')
        this.refresh()
      } catch (error) {
        this.handleError(error, '课程修改失败')
      } finally {
        this.dialogCfg.loading = false
      }
    },

    refresh() {
      this.dialogCfg.visible = false
      this.getCourseList()
    },

    async createOrUpdateCourse(data) {
      const res = await createOrUpdateCourse(data)
        .catch(err => {
          throw new Error(err.response.data.message)
        })
      if (res.code !== 200) {
        throw new Error(res.message)
      }
      return res
    },

    removeCourse(row) {
      this.$confirm('是否删除该课程？', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let ids = null
        if (isArray(row)) ids = JSON.stringify(row)
        else ids = JSON.stringify([row.id])
        this.deleteCourse({ ids })
      })
    },

    async deleteCourse(ids) {
      try {
        const res = await deleteCourse(ids)
        if (res.code === 200) {
          this.$message.success('删除成功')
          this.selected = []
          this.clearSelection()
          this.pagination.page = 1
          await this.getCourseList()
        }
      } catch (error) {
        this.handleError(error, '删除失败')
      }
    },

    clearSelection() {
      this.$refs.elTableRef.clearSelection()
    },

    handleSelectionChange(e) {
      this.selected = e.map(item => item.id)
    },

    async editCourse(row) {
      const dataFormatter = (data) => {
        return data.map(item => {
          return {
            name: item.name,
            sort: item.sort,
            duration: item.duration.map(duration => {
              return {
                name: duration.name,
                path: duration.path,
                id: duration.video_id
              }
            })
          }
        })
      }

      try {
        const res = await this.getCourseDetails(row.id)
        const { chapter, cover, day, title, id } = res.data
        const params = {
          course_id: id,
          title,
          cover,
          day,
          data: dataFormatter(chapter)
        }
        this.dialogCfg.visible = true
        this.$nextTick(() => {
          this.$refs.courseDialogRef.setDefaultSectionData(params)
        })
      } catch (error) {
        this.handleError(error, '获取课程详情失败')
      }
    },

    async getCourseDetails(id) {
      const res = await getCourseDetails(id)
        .catch(err => {
          throw new Error(err)
        })
      if (res.code !== 200) throw new Error('课程详情获取失败')
      return res
    }
  }

}
</script>
<style scoped lang='scss'>

.course-list {
  padding: 20px;
  &__operate {
    margin-bottom: 20px;
  }
}
.course-form {
  .el-form-item {
    margin-bottom: 0;
  }
}
</style>
